<template>
  <div class="app-container">
    <el-button  class="filter-item marginRB10" type="primary" icon="el-icon-plus" @click="handleCreate()">
      添加
    </el-button>
    <el-button class="marginRB10" type="danger" @click="allDel()" plain>批量删除</el-button>
    <el-select filterable v-model="listQuery.sold" class="filter-item marginRB10" placeholder='请选择状态'
               style="width: 200px;">
      <el-option v-for="item in selectList" :key="item.key" :label="item.lab" :value="item.key"></el-option>
    </el-select>
    <el-select filterable v-model="listQuery.type" class="filter-item marginRB10" placeholder='请选择类别'
               style="width: 200px;">
      <el-option v-for="item in selectList2" :key="item.id" :label="item.name" :value="item.id"></el-option>
    </el-select>
    <el-input class="marginRB10" v-model="listQuery.name" placeholder="请输入礼物名称" style="width:200px;"
              clearable></el-input>
    <el-button type="primary" @click="getList" icon="el-icon-search"  class="marginRB10">搜索</el-button>

    <el-table ref="dataList" :data="menuList" style="margin-bottom: 20px;" row-key="id" border
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="序号"></el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="picture" label="图片">
        <template slot-scope="scope">
          <el-popover placement="right" max-width="220" trigger="hover">
            <img :src="scope.row.picture" alt="" style="max-width: 200px;max-height: 200px">
            <img slot="reference" :src="scope.row.picture" alt="" style="width: 50px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="special" label="效果">
        <template slot-scope="scope">
          <el-popover placement="right" max-width="220" trigger="hover">
            <img :src="scope.row.special" alt="" style="max-width: 200px;max-height: 200px">
            <img slot="reference" :src="scope.row.special" alt="" style="width: 50px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column prop="type" label="类别"></el-table-column>
      <el-table-column prop="sold" label="状态">
        <template slot-scope="scope">
          {{ scope.row.sold === 1 ? '上架' : '下架' }}
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序"></el-table-column>

      <el-table-column min-width="280" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)" plain>编辑
          </el-button>
          <el-button v-if="scope.row.sold === 2" type="success" size="mini" @click="upDown(scope.row, 1)" plain>上架
          </el-button>
          <el-button v-if="scope.row.sold === 1" type="warning" size="mini" @click="upDown(scope.row, 2)" plain>下架
          </el-button>
          <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.perPage"
                    @pagination="getList"/>

    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible"
               @close="handleDialogClose">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="120px"
               style="width: 400px; margin: 0 auto;">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" maxlength="30" show-word-limit/>
        </el-form-item>
        <el-form-item label='图片' prop="picture">
          <img v-if="form.picture&&!form.picture.name" :src="form.picture" alt=""
               style="max-width: 200px;max-height: 200px">
          <span v-else>{{ form.picture ? form.picture.name : '' }}</span>
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label='效果' prop="special">
          <img v-if="form.special&&!form.special.name" :src="form.special" alt=""
               style="max-width: 200px;max-height: 200px">
          <span v-else>{{ form.special ? form.special.name : '' }}</span>
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess2"
            :before-upload="beforeAvatarUpload2">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label='价格' prop="price">
          <el-input v-model="form.price" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="类别" prop="type">
          <el-select filterable v-model="form.type" class="filter-item" placeholder='请选择类别' style="width: 280px;">
            <el-option v-for="item in selectList3" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="form.sort" placeholder="请输入排序"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {saveData, deleteData, updateData, listData, upDowmData, typeList} from '@/api/gift/gift'

export default {
  data() {
    return {
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10
      },
      selectList: [{key: undefined, lab: '全部上架状态'}, {key: '1', lab: '上架'}, {key: '2', lab: '下架'}],
      selectList2: [],
      selectList3: [],
      menuList: [{id: '1', name: '1', picture: '1', special: '1', price: '1', type: '1', sold: '1', sort: '1',}],
      dialogFormVisible: false,
      dialogStatus: '',
      titleMap: {
        update: '编辑',
        create: '增加'
      },
      form: {
        id: undefined,
        name: undefined,
        picture: undefined,
        special: '',
        price: '',
        type: undefined,
        sold: undefined,
        sort: undefined,
      },
      rules: {
        name: [{required: true, message: '请输入名称', trigger: 'blur'}, {
          min: 1,
          max: 30,
          message: '长度在 1 到 30 个字符',
          trigger: 'blur'
        }],
        picture: [{required: true, message: '请上传图片', trigger: 'blur'}],
        special: [{required: true, message: '请输入效果', trigger: 'blur'}],
        price: [{required: true, message: '请输入价格', trigger: 'blur'}],
        type: [{required: true, message: '请输入类别', trigger: 'blur'}],
      }
    }
  },
  created() {
    this.getList()
    this.getTypeList()
  },
  methods: {
    handleAvatarSuccess(res, file) {
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      this.form.picture = file
    },
    handleAvatarSuccess2(res, file) {
    },
    beforeAvatarUpload2(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      this.form.special = file
      // return isJPG && isLt2M;
    },
    getTypeList() {
      typeList().then(response => {
        this.selectList2 = [{id: undefined, name: '全部分类'}, ...response.data]
        this.selectList3 = response.data
      })
    },
    getList() {
      this.listLoading = true
      listData(this.listQuery).then(response => {
        this.menuList = response.data.list
        this.total = response.data.meta.total;
        this.listLoading = false
      })
    },
    handleCreate(row) {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {

      this.form = []
      this.form.id = row.id
      this.form.name = row.name
      this.form.picture = row.picture
      this.form.special = row.special
      this.form.price = row.price
      this.form.type = row.type
      // this.form.sold= row.sold
      this.form.sort = row.sort

      this.dialogStatus = 'update'
      this.dialogFormVisible = true

      this.form = Object.assign({}, this.form)
    },
    handleDelete(row) {
      let data = {ids: row.id}
      deleteData(data).then(response => {
        if (response.code === 200) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          });
        }
      })
    },
    allDel() {
      let delNum = []
      this.$refs.dataList.selection.forEach((k) => {
        delNum.push(k.id)
      })
      if (delNum.length === 0) {
        return;
      }
      let data = {ids: delNum.toString()}
      deleteData(data).then(response => {
        if (response.code === 200) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          });
        }
      })
    },
    submitForm() {
      // this.form)
      // return;
      this.$refs['dataForm'].validate(valid => {
        if (valid && this.dialogStatus === 'create') {
          let formData = new FormData();
          for (let item in this.form) {
            this.form[item] === undefined ? '' : formData.append(item, this.form[item]);
          }
          saveData(formData).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              });
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              });
            }
          })
        } else if (valid && this.dialogStatus === 'update') {

          let formData = new FormData();
          for (let item in this.form) {
            this.form[item] === undefined ? '' : formData.append(item, this.form[item]);
          }
          updateData(formData).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              });
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              });
            }
          })
        }
      })
    },
    upDown(row, type) {
      let data = {id: row.id, sold: type}
      upDowmData(data).then(response => {
        if (response.code === 200) {
          this.getList()
          this.submitOk('操作成功')
        } else {
          this.submitFail('操作失败')
        }
      })
    },
    resetForm() {
      this.form = {
        id: undefined,
        name: undefined,
        picture: '',
        special: '',
        price: undefined,
        type: undefined,
        sold: undefined,
        sort: undefined,
      }
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
      }
    }
  }
}
</script>
